/**
 * Created by xinxinran on 2016/12/14.
 */
'use strict';
const express = require('express'),
    co = require('co'),
    router = express.Router(),
    daoUtil = require('../dao');

router.all('/', co.wrap(function* (req, res, next){
    let baseApiUrl = req.baseUrl, dao, daoDbName,  targetIfObj;

    if(baseApiUrl.startsWith('/api-')){
        let daoDbInfo = /^\/api-([^/]+)(\/.*)$/.exec(baseApiUrl);
        daoDbName = daoDbInfo && daoDbInfo[1];
        baseApiUrl = daoDbInfo[2];
    }

    dao = daoUtil.getDao(daoDbName);

    res.writeHead(200, {'Content-Type':'application/json;charset=utf-8'});
    try{
        targetIfObj = yield dao.getInterfaceByUrl(baseApiUrl);
        if(targetIfObj){
            res.end(targetIfObj.resultDemo);
        }else{
            res.end(JSON.stringify({code : 'IF-ERROR', msg : '404'}));
        }
    }catch (e){
        res.end(JSON.stringify({code : 'FATAL-ERROR', msg : e}));
    }

}));

module.exports = router;